<?php
/**
 * @author Voislav Jovanovic <voislavj@gmail.com>
 * main entry point for the framework
 */

session_start();
ob_start();

require_once "constants.php";
require_once "functions.php";

class Dispatcher {
	
	private static $instance;
	public $uri = array(
		"controller" => "",
		"action" => "",
		"params" => array()
	);
	
	private static function getInstance(){
		if(!self::$instance){
			self::$instance = new self();
		}
		return self::$instance;
	}

	public static function dispatch(){
		$D = self::getInstance();
		$D->parseURL();
		
		try {
			$className = file2class($D->uri->controller) . "Controller";
			$controller = new $className;
			$controller->_dispatcher = $D;
			
			// load models, if there'are models to load
			if(count($controller->models)) {
				foreach($controller->models as $model) {
					$controller->loadModel($model);
				}
			}
			
			// call the method if it's defined
			if(method_exists($controller, $D->uri->action)) {
				$toeval = "\$controller->{$D->uri->action}(";
				foreach($D->uri->params as $p) {
					$pe = str_replace("'", "\\'", $p);
					if(preg_match('/^\d+(\.\d+)?$/', $p)) {
						$toeval .= "$p,";
					} else {
						$toeval .= "'$pe',";
					}
				}
				$toeval = preg_replace('/,$/', "", $toeval) . ");";
				eval($toeval);
			}
			
			if($controller->autoRender) {
				echo $controller->render();
			}
			
		} catch(Exception $e) {
			echo "<h1>{$e->getMessage()}</h1>";
			echo "<p>" . nl2br($e->getTraceAsString()) . "</p>";
		}
	}
	
	public function parseURL(){
		$url = $_GET["__req"];
		$url_items = explode("/", $url);
		
		$this->uri["controller"] = $url_items[0] ? $url_items[0] : DEFAULT_CONTROLLER;
		$this->uri["action"] = $url_items[1] ? $url_items[1] : DEFAULT_ACTION;
		$this->uri["params"] = array_slice($url_items, 2);
		
		$this->uri = (Object)$this->uri;
	}
}

?>